package com.fowo.api.syncAmazon.api;

import com.amazon.spapi.api.ReportsApi;
import com.amazon.spapi.client.ApiException;
import com.amazon.spapi.model.reports.CreateReportResponse;
import com.amazon.spapi.model.reports.CreateReportSpecification;
import com.amazon.spapi.model.reports.Report;
import com.fowo.api.entity.ShopInfo;

import java.io.IOException;

public abstract class ReportService {

    /**
     * 创建报告
     * @param ReportsApi
     * @param body
     * @return 报告id
     * @throws ApiException
     */
    public String createReport(ReportsApi ReportsApi, CreateReportSpecification body) throws ApiException {

        CreateReportResponse response = ReportsApi.createReport(body);
        return response.getReportId();
    }

    /**
     * 检查报告是否处理完成
     * @param ReportsApi
     * @param reportId
     * @return
     * @throws Exception
     */
    public Report getReport(ReportsApi ReportsApi, String reportId) throws Exception {
        Report report = ReportsApi.getReport(reportId);
        if(report.getProcessingStatus().getValue().equals("IN_PROGRESS")  //报告正在处理中
                || report.getProcessingStatus().getValue().equals("IN_QUEUE")) //报告尚未开始处理
        {
            Thread.currentThread().sleep(5000); //等1S再请求
            return getReport(ReportsApi,reportId);
        }

        if(report.getProcessingStatus().getValue().equals("DONE")){
            return report;
        }else if(report.getProcessingStatus().getValue().equals("FATAL")){
            throw new Exception("获取报告失败！");
        }else if(report.getProcessingStatus().getValue().equals("CANCELLED")) {
            throw new Exception("无可用数据！");
        }else{
            throw new Exception("未知异常！");
        }
    }

    public abstract void download(String url, String compressionAlgorithm, ShopInfo shop) throws IOException, IllegalArgumentException;
}
